﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Company.Project.Domain.Base;
using Company.Project.Domain.MainModule.Interface;
using Company.Project.Domain.Model;
using Company.Project.Domain.Model.DTO;
using Company.Project.Infrastructure.Repository.Sqlserver.DataBaseFactory;
using Company.Project.Infrastructure.Repository.Sqlserver.RepositoriesBase;
using Company.Utility;
using Company.Project.Infrastructure.Common;
using Company.Project.Infrastructure.Common.Enums;

namespace Company.Project.Infrastructure.Repository.Sqlserver
{
    public class Project_SYS_PhoneMessageRecordRepository : RepositoryBase<Project_SYS_PhoneMessageRecord>, IProject_SYS_PhoneMessageRecordRepository
    {
        public Project_SYS_PhoneMessageRecordRepository(IDatabaseFactory databaseFactory)
            : base(databaseFactory)
        {

        }

        public async Task<bool> CheckCodeValidity(string phone, string code, Enum_PhoneMessageSendType sendType,
            Enum_PhoneMessageSendUserType sendUserType, string openId, Guid? userId)
        {
            if (string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(code))
            {
                throw new CustomException("请填写手机号码与短信验证码!");
            }
            switch (sendUserType)
            {
                case Enum_PhoneMessageSendUserType.Manager:
                    if (userId == null)
                    {
                        throw new CustomException("登录失效,请重新登录后再试!");
                    }
                    break;
                case Enum_PhoneMessageSendUserType.WeChatMember:
                    if (userId == null || string.IsNullOrEmpty(openId))
                    {
                        throw new CustomException("微信授权过期,请关闭微信后再试!");
                    }
                    break;
            }
            var count =(await
                GetManyAsync(
                    new DirectSpecification<Project_SYS_PhoneMessageRecord>(
                        x =>
                            !x.IsDeleted && x.SendOpenId == openId && x.SendUserId == userId && x.SendType == sendType &&
                            x.SendUserType == sendUserType && x.Code == code && x.SendPhoneNumber == phone))).OrderByDescending(x=>x.SendTime).FirstOrDefault();
            if (count == null || count.ID == Guid.Empty)
            {
                throw new CustomException("没有查询到发送记录,请重新发送!");
            }
            if (count.SendTime.AddMinutes(SystemParameterHelper.MsgPastTime) < DateTime.Now)
            {
                throw new CustomException("验证码已超过有效时间,请重新发送!");
            }
            count.IsDeleted = true;
            Update(count,x=>x.IsDeleted);
            return true;
        }
    }
}